const mongoose = require('mongoose');

const connectDB = async () => {
    try {
        const conn = await mongoose.connect(process.env.MONGODB_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            serverSelectionTimeoutMS: 5000,
            retryWrites: true
        });

        console.log(`MongoDB Connected: ${conn.connection.host}`);
    } catch (error) {
        console.error(`MongoDB Connection Error: ${error.message}`);
        if (error.name === 'MongoServerSelectionError') {
            console.error('请检查：');
            console.error('1. MongoDB 服务是否正在运行');
            console.error('2. 数据库用户名和密码是否正确');
            console.error('3. MongoDB 是否开启了认证模式');
        }
        process.exit(1);
    }
};

module.exports = connectDB; 